# Copyright (C) 2006  Apptility LLC  http://www.apptility.com
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

class DbbackupDeliveryUtil < ActiveRecord::Base
 
  def self.deliver_schedule
    AjubyLogger.logInfo "\nDelivering daily backup!\n"
    #logData("Delivering daily backup!")
    deliver_base()
  end 
      
  def self.deliver_base()
        
        #id=1
        
        users = Dbbackup.find(:all)#, :conditions => [ "id = ?", id])
           
        fname=""
        lname=""
        email=""
        
        users.each {|user| 
        fname="#{user.firstname}"
        lname="#{user.lastname}"
        email="#{user.email}"
        }
        
       
        @db_config = ActiveRecord::Base.configurations[RAILS_ENV]
  
        datestamp = Time.now.strftime("%Y-%m-%d_%H-%M-%S")
        
        FileUtils.rm_rf("#{RAILS_ROOT}/db/backup")
              
        if(!File.exist?("#{RAILS_ROOT}/db/backup"))
          Dir.mkdir("#{RAILS_ROOT}/db/backup")
        end
   
        path="#{RAILS_ROOT}/db/backup"     

        backup_folder =  File.join("#{path}",datestamp)
   
        if(!File.exist?("#{backup_folder}"))
          Dir.mkdir("#{backup_folder}")
        end
   
          
        if(@db_config['adapter']=="mysql")
          system("mysqldump -u #{@db_config['username']} -p#{@db_config['password']} -h #{@db_config['host']} #{@db_config['database']} > #{backup_folder}/dbbackup.sql")
        else
          system("pg_dump -U #{@db_config['username']} -h #{@db_config['host']} #{@db_config['database']} > #{backup_folder}/dbbackup.sql")
        end
   
        Zlib::GzipWriter.open("#{backup_folder}/#{RAILS_ENV}_structure.sql.gz") do |gz|
          gz.write(File.read("#{backup_folder}/dbbackup.sql"))
        end
  
        File.delete("#{backup_folder}/dbbackup.sql")
        
        size = File.size("#{backup_folder}/#{RAILS_ENV}_structure.sql.gz")
        
        backupfile="#{backup_folder}/#{RAILS_ENV}_structure.sql.gz"       
        
        filename = "#{RAILS_ENV}_structure.sql.gz"
        
        DbbackupDeliver.deliver_backupemail(email,fname,lname,size,filename,backupfile)
  end
   

end
